<template>
	<view class="app-container">
		<!-- 顶部导航栏 -->

		<view class="header">
			<view class="location-container" @tap="chooseLocation">
				<text class="location-text">{{ currentCity }}</text>
				<view class="arrow-icon">▼</view>
			</view>
			<view class="header-content">
				<view class="app-title">韩盈贸易</view>
			</view>
		</view>

		<!-- 用户菜单弹出层 -->
		<view v-if="showUserMenu" class="user-menu">
			<view class="menu-item" v-for="(item, index) in menuItems" :key="index" @tap="onMenuItemTap(item)">
				<view class="menu-item-icon">{{ item.icon }}</view>
				<text class="menu-item-text">{{ item.name }}</text>
			</view>
			<view class="menu-item logout" @tap="logout">
				<view class="menu-item-icon">🚪</view>
				<text class="menu-item-text">退出登录</text>
			</view>
		</view>

		<!-- 地图区域 -->
		<view class="map-wrapper">
			<map id="myMap" class="map" :latitude="latitude" :longitude="longitude" :markers="markers" :scale="16"
				show-location enable-zoom enable-scroll :enable-rotate="false" :enable-3D="false"
				:enable-overlooking="false" :enable-satellite="false" :enable-traffic="false" enable-poi
				:show-compass="false" @tap="onMapTap" @regionchange="onMapRegionChange" @markertap="markersClick">
			</map>

			<!-- 快捷操作按钮区 -->
			<view class="map-controls">
				<view class="control-button locate-button" @tap="getCurrentLocation">
					<uni-icons type="location" size="20"></uni-icons>
				</view>
				<view class="control-button refresh-button" @tap="loadNearbyVehicles">
					<uni-icons type="refreshempty" size="20"></uni-icons>

				</view>
			</view>

			<!-- 地图图例说明 -->
			<view class="map-legend">
				<view class="legend-item">
					<view class="legend-marker active"></view>
					<text class="legend-text">站点位置</text>
				</view>
				<view class="legend-item">
					<view class="legend-marker current"></view>
					<text class="legend-text">当前位置</text>
				</view>
			</view>
		</view>

		<!-- 底部操作区 -->
		<view class="bottom-panel">
			<view class="panel-content">
				<!-- 用户信息区 -->
				<view v-if="isLoggedIn" class="user-profile-container" @tap="toggleUserMenu">
					<image class="user-avatar" :src="userInfo.avatarUrl" mode="aspectFill"></image>
					<view class="user-info">
						<text class="user-name">{{ userInfo.nickName }}</text>
						<text class="user-status">已登录</text>
					</view>
					<view class="user-menu-icon">⋮</view>
				</view>

				<!-- 扫码用车按钮 -->
				<template v-if="isLoggedIn">
					<button v-if="userInfo.mobile" class="primary-button" @tap="onRentTap">
						<text class="button-icon"></text>
						<text class="button-text">自助租赁扫码用车</text>
					</button>
					<button v-else class="primary-button" open-type="getPhoneNumber" @getphonenumber="bindMobile">
						<text class="button-icon"></text>
						<text class="button-text">自助租赁扫码用车</text>
					</button>
				</template>
				<template v-else>
					<!-- 登录按钮 -->
					<view style="display: flex; align-items: center;">
						<button class="login-button-large" @tap="directWxLogin">
							<text class="button-icon">👤</text>
							<text class="button-text">登录使用</text>
						</button>
						<button class="login-button-large" @tap="onMenuItemTap(menuItems[1])">
							<text class="button-icon">💬</text>
							<text class="button-text">服务中心</text>
						</button>
					</view>
				</template>
			</view>
		</view>

		<view class="station-panel" :class="{ 'panel-visible': showStationPanel }">
			<!-- 关闭按钮 -->
			<view class="close-btn" @tap="showStationPanel = false">
				<uni-icons type="close" size="24" color="#666"></uni-icons>
			</view>

			<!-- 面板内容 -->
			<scroll-view scroll-y class="panel-content">
				<view class="station-header">
					<text class="station-title" v-if="currentStation">{{ currentStation.title }}</text>
					<view class="status-tag" v-if="currentStation">
						可用
					</view>
				</view>

				<view class="info-row">
					<uni-icons type="location" size="16" color="#666"></uni-icons>
					<text class="info-text">{{ currentStation.geographic.address }}</text>
				</view>

				<view class="info-row">
					<uni-icons type="car" size="16" color="#666"></uni-icons>
					<text class="info-text" v-if="currentStationDetail">
						可用车辆：{{ currentStationDetail.length }}
					</text>
					<text class="info-text" v-else>
						可用车辆：0
					</text>
				</view>
			</scroll-view>

		</view>

		<!-- 遮罩层 -->
		<view class="panel-mask" :class="{ 'mask-visible': showStationPanel }" @tap="showStationPanel = false"></view>
	</view>
</template>

<script>
function parseInput(data) {
	// 尝试解析 JSON
	try {
		const json = JSON.parse(data);
		if (typeof json === 'object' && json !== null) {
			return json;
		}
	} catch (e) {
		// 不是 JSON，继续
	}

	// 尝试手动解析 URL 参数
	const queryIndex = data.indexOf('?');
	if (queryIndex !== -1) {
		const queryStr = data.substring(queryIndex + 1);
		const params = {};
		const pairs = queryStr.split('&');
		for (const pair of pairs) {
			const [key, value] = pair.split('=');
			if (key) {
				params[decodeURIComponent(key)] = decodeURIComponent(value || '');
			}
		}
		return params;
	}

	// 都不是
	return null;
}


import {
	WX_CONFIG,
	API_CONFIG,
	STORAGE_KEYS
} from '@/config/constants.js';

const QQMapKey = 'X2BBZ-P6XKB-IPGUL-JVUUO-ZXXSZ-EIFIX'; // 保持原来的key

// #ifdef H5
// 动态加载腾讯地图SDK（仅在H5环境中使用）
const loadQQMapScript = () => {
	return new Promise((resolve, reject) => {
		if (window.qq && window.qq.maps) {
			resolve(window.qq.maps);
			return;
		}
		const script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = `https://map.qq.com/api/js?v=2.exp&key=${QQMapKey}`;
		script.onload = () => resolve(window.qq.maps);
		script.onerror = reject;
		document.head.appendChild(script);
	});
};
// #endif

export default {
	data() {
		return {
			// 地图相关
			currentCity: '定位中...',
			latitude: 0, //29.325071026714276, // 修正：纬度值
			longitude: 0, //120.01002187626707, // 修正：经度值
			markers: [],
			// 用户相关
			isLoggedIn: false,
			userInfo: null,
			showUserMenu: false,

			// 菜单项
			menuItems: [{
				name: '我的订单',
				icon: '📋'
			},
			{
				name: '服务中心',
				icon: '💬'
			},
			],

			// 控制变量
			hasLocationAuth: true,
			isUserAction: false,
			updateTimer: null,
			lastUpdateTime: 0,
			isMapLoaded: false,
			blockLocationUpdate: false,
			usingStaticCityName: false, // 是否使用静态城市名
			apiKeyLimited: false, // 标记API密钥是否受限

			showStationPanel: false,
			currentStation: {
				geographic: 0
			},
			currentStationDetail: null,
		};
	},

	onLoad() {
		// #ifdef H5
		this.initMapSDK();
		// #endif

		// 检查登录状态
		this.checkLoginStatus();

		// 创建地图上下文
		this.mapContext = uni.createMapContext('myMap', this);

		// 初始化地图
		// console.log('初始化地图, 初始坐标:', this.latitude, this.longitude);

		// 直接初始化地图和获取位置，不使用setTimeout
		this.getCurrentLocation();
		this.isMapLoaded = true;
	},

	methods: {
		// #ifdef H5
		async initMapSDK() {
			try {
				await loadQQMapScript();
				// console.log('腾讯地图SDK加载成功');
			} catch (err) {
				// console.error('腾讯地图SDK加载失败：', err);
				uni.showToast({
					title: '地图加载失败',
					icon: 'none'
				});
			}
		},
		// #endif

		// 用户相关方法
		async checkLoginStatus() {
			const token = uni.getStorageSync(STORAGE_KEYS.token);
			this.isLoggedIn = !!token;
			if(this.isLoggedIn){
				//获取用户信息
				let _this = this
				uni.request({
					url: API_CONFIG.baseUrl + '/user.User/detail',
					method: 'POST',
					header: {
						'content-type': 'application/json' // 明确指定内容类型
					},
					data: {
						token:token
					},
					timeout: API_CONFIG.timeout,
					success: (res) => {
						if (res.data && res.data.code === 1) {
							const userData = res.data.data.userInfo;
							if(!userData || !userData.user_id){
								return _this.wxLogin();
							}
							const userInfoToSave = {
								...userData,
								userId: userData.user_id || 0
							};
							uni.setStorageSync(STORAGE_KEYS.userInfo, userInfoToSave);
							console.log("userInfoToSave",userData,userInfoToSave)
							this.userInfo = userInfoToSave;
							this.isLoggedIn = true;
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});
						} else {
							// 登录失败
							_this.wxLogin();
						}
					},
					fail: (err) => {
						_this.wxLogin();
					}
				});
			}
			else{
				//this.wxLogin();
			}
			/*const userInfo = uni.getStorageSync(STORAGE_KEYS.userInfo);
			this.isLoggedIn = !!token;
			if (this.isLoggedIn && userInfo) {
				this.userInfo = userInfo;
				const expiretime = uni.getStorageSync(STORAGE_KEYS.expiretime);
				if (!expiretime || expiretime < Date.now()) {
					//重新登录
					this.isLoggedIn = false;
					uni.removeStorageSync(STORAGE_KEYS.token);
					uni.removeStorageSync(STORAGE_KEYS.userInfo);
					this.wxLogin();
				}
			}*/
		},

		// 直接微信登录方法，解决getUserProfile问题
		directWxLogin() {
			// #ifdef MP-WEIXIN
			const accountInfo = uni.getAccountInfoSync();
			// console.log(accountInfo)
			// 立即调用getUserProfile，不在异步回调中调用
			wx.getUserProfile({
				desc: '用于完善会员资料',
				lang: 'zh_CN',
				success: (res) => {
					console.log(res);
					// 构建标准化的用户信息对象
					const userInfo = {
						nickName: res.userInfo.nickName || '用户',
						avatarUrl: res.userInfo.avatarUrl || '',
						gender: res.userInfo.gender || 0,
						country: res.userInfo.country || '中国',
						province: res.userInfo.province || '',
						city: res.userInfo.city || '',
						language: res.userInfo.language || 'zh_CN',
						mobile: res.userInfo.mobile || ''
					};

					// 保存用户信息
					this.userInfo = userInfo;
					uni.setStorageSync(STORAGE_KEYS.userInfo, userInfo);
					// console.log(this.userInfo)
					// 继续获取登录code
					this.getLoginCode(userInfo);
				},
				fail: (err) => {
					console.error('用户拒绝授权:', err);
					uni.showModal({
						title: '授权提示',
						content: '您拒绝了授权登录，无法使用该功能。请允许微信授权以继续使用完整功能。',
						showCancel: false
					});

					// 用户拒绝授权，不进行后续登录尝试
					return;
				}
			});
			// #endif

			// #ifndef MP-WEIXIN
			// 非微信环境下改为使用常规登录方法
			uni.showModal({
				title: '提示',
				content: '当前环境不支持微信登录',
				showCancel: false
			});
			// #endif
		},

		// 获取登录凭证方法
		getLoginCode(userInfo) {
			uni.showLoading({
				title: '登录中...'
			});

			uni.login({
				provider: 'weixin',
				success: (res) => {
					console.log("获取登录凭证res", res);
					// 发送给服务器
					this.serverLogin(res.code, userInfo);
				},
				fail: (err) => {
					uni.hideLoading();
					uni.showModal({
						title: '登录失败',
						content: '获取登录凭证失败，请检查网络并重试。',
						showCancel: false
					});
					// console.error('获取登录凭证失败:', err);
				}
			});
		},

		// 传统微信登录方法（主要用于非小程序环境）
		wxLogin() {
			uni.showLoading({
				title: '登录中...'
			});

			// 获取登录凭证
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					// console.log('登录成功，获取code：', loginRes.code);

					// 非微信小程序环境，使用uni-app API
					uni.getUserInfo({
						provider: 'weixin',
						success: (infoRes) => {
							console.log('获取用户信息成功：', infoRes);
							this.userInfo = infoRes.userInfo;

							// 保存用户信息到本地
							uni.setStorageSync(STORAGE_KEYS.userInfo, infoRes.userInfo);

							// 发送code和用户信息到服务器换取登录态
							this.serverLogin(loginRes.code, infoRes.userInfo);
						},
						fail: (err) => {
							console.error('获取用户信息失败：', err);
							uni.hideLoading();
							uni.showModal({
								title: '授权提示',
								content: '您拒绝了获取个人信息，无法使用该功能。请允许获取个人信息以继续使用完整功能。',
								showCancel: false
							});
						}
					});
				},
				fail: (err) => {
					console.error('微信登录失败：', err);
					uni.hideLoading();
					uni.showModal({
						title: '登录失败',
						content: '微信登录授权失败，请检查网络并重试。',
						showCancel: false
					});
				}
			});
		},

		// 服务器登录方法
		serverLogin(code, userInfo) {
			// 确保userInfo是一个对象
			const safeUserInfo = userInfo || {};
			// 准备请求数据
			const requestData = {
				code: code,
				appid: WX_CONFIG.appId,
				secret: WX_CONFIG.appSecret,
				user_info: JSON.stringify({
					nickName: safeUserInfo.nickName || '游客',
					avatarUrl: safeUserInfo.avatarUrl || '',
					gender: safeUserInfo.gender || 0,
					country: safeUserInfo.country || '中国',
					province: safeUserInfo.province || '',
					city: safeUserInfo.city || '',
					language: safeUserInfo.language || 'zh_CN'
				}), // 将用户信息转为JSON字符串
				source: 'wxapp', // 添加来源参数
			};

			uni.request({
				url: API_CONFIG.baseUrl + API_CONFIG.loginUrl,
				method: 'POST',
				header: {
					'content-type': 'application/json' // 明确指定内容类型
				},
				data: requestData,
				timeout: API_CONFIG.timeout,
				success: (res) => {
					uni.hideLoading();
					console.log('服务器登录响应：', res);
					console.log("token为", res.data.data.token)
					if (res.data && res.data.code === 1) {
						// 保存token和用户信息
						const userData = res.data.data;
						uni.setStorageSync(STORAGE_KEYS.token, userData.token || '');
						const now = new Date().getTime();
						// 计算7天后的时间戳
						const sevenDaysLater = now + 7 * 24 * 60 * 60 * 1000;
						uni.setStorageSync(STORAGE_KEYS.expiretime, sevenDaysLater);		//有效时间7天
						// 如果服务器返回了用户信息，使用服务器的数据，否则使用本地数据
						const userInfoToSave = {
							...safeUserInfo,
							...userData,
							userId: userData.id || userData.userId || 0
						};
						uni.setStorageSync(STORAGE_KEYS.userInfo, userInfoToSave);
						this.userInfo = userInfoToSave;
						this.isLoggedIn = true;
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
					} else {
						// 登录失败
						uni.showModal({
							title: '登录失败',
							content: res.data?.msg || '服务器登录失败，请稍后重试。',
							showCancel: false
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					console.error('服务器登录失败：', err);

					// 登录失败
					uni.showModal({
						title: '登录失败',
						content: '网络错误，无法连接到服务器，请检查网络并重试。',
						showCancel: false
					});
				}
			});
		},

		toggleUserMenu() {
			this.showUserMenu = !this.showUserMenu;
		},

		logout() {
			uni.showModal({
				title: '退出登录',
				content: '确定要退出当前账号吗？',
				success: (res) => {
					if (res.confirm) {
						this.isLoggedIn = false;
						this.userInfo = null;
						this.showUserMenu = false;
						uni.removeStorageSync(STORAGE_KEYS.userInfo);
						uni.removeStorageSync(STORAGE_KEYS.token);
						uni.showToast({
							title: '已退出登录',
							icon: 'success'
						});
					}
				}
			});
		},

		// 地图相关方法
		getCurrentLocation() {
			uni.showLoading({
				title: '定位中...'
			});

			this.blockLocationUpdate = true;

			uni.getLocation({
				type: 'gcj02', // 修改为gcj02坐标系，更适合中国地图
				success: (res) => {
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.hasLocationAuth = true;
					this.updateCurrentCity();
					this.loadNearbyVehicles();
				},
				fail: (err) => {
					console.error('获取位置失败：', err);
					this.hasLocationAuth = false;

					// 判断错误类型
					if (err.errMsg && err.errMsg.includes('auth deny')) {
						// 权限被拒绝
						uni.showModal({
							title: '定位权限提示',
							content: '需要获取您的位置才能查找附近的溜娃车，请在设置中开启定位权限。',
							confirmText: '去设置',
							cancelText: '取消',
							success: (res) => {
								if (res.confirm) {
									// 打开设置页面
									uni.openSetting({
										success: (settingRes) => {
											// console.log('设置结果:', settingRes);
											if (settingRes.authSetting[
												'scope.userLocation']) {
												// 用户在设置中打开了权限，重新获取位置
												setTimeout(() => {
													this
														.getCurrentLocation();
												}, 500);
											}
										}
									});
								} else {
									// 用户取消，仍然尝试加载车辆
									this.loadNearbyVehicles();
								}
							}
						});
					} else {
						// 其他错误
						uni.showToast({
							title: '获取位置失败，使用默认位置',
							icon: 'none',
							duration: 2000
						});

						// 即使获取位置失败，也尝试加载车辆
						this.loadNearbyVehicles();
					}
				},
				complete: () => {
					uni.hideLoading();
					setTimeout(() => {
						this.blockLocationUpdate = false;
					}, 1000);
				}
			});
		},

		updateCurrentCity() {
			// 如果API密钥已经被标记为受限，直接使用静态城市名
			if (this.apiKeyLimited) {
				this.currentCity = '当前城市';
				return;
			}
			const mapCtx = uni.createMapContext('myMap');
			mapCtx.getCenterLocation({
				success: (res) => {

					uni.request({
						// url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${QQMapKey}`,
						url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + this.latitude +
							"," + this.longitude + "&key=AUGBZ-AD3EZ-MT6XQ-TMFGS-XB6M2-3OFJK",
						success: (res) => {
							console.log(res);
							// 检查API密钥是否超限
							if (res.data && (res.data.status === 121 || res.data.message ===
								"此key每日调用量已达到上限")) {
								console.warn('腾讯地图API密钥已达调用上限');
								console.log("获取当前位置", res);
								this.currentCity = '当前城市';
								this.apiKeyLimited = true; // 标记API密钥受限

								// 如果因为API限制导致站点名称未显示，则重新加载车辆
								this.loadNearbyVehicles();
							} else if (res.data && res.data.result && res.data.result
								.address_component) {
								this.currentCity = res.data.result.address_component.city ||
									'未知城市';
							}
						},
						fail: (err) => {
							console.error('地理编码请求失败:', err);
							this.currentCity = '当前城市';
						}
					});
				},
				fail: (err) => {
					console.error('获取地图中心位置失败:', err);
					this.currentCity = '当前城市';
				}
			});
		},

		loadNearbyVehicles() {
			uni.showLoading({
				title: '加载车辆中...'
			});

			// 从本地存储获取API基础URL
			const apiBaseUrl = uni.getStorageSync(STORAGE_KEYS.ip) || API_CONFIG.baseUrl;
			// console.log('API地址:', apiBaseUrl);

			// 请求API获取车辆数据
			uni.request({
				url: apiBaseUrl + '/babyCar.station/list',
				method: 'GET',
				success: (res) => {
					if (res.data && res.data.code === 1 && Array.isArray(res.data.data)) {
						// 处理返回的车辆数据
						this.stationData = res.data.data;
						// console.log("返回的地图标记点信息", this.stationData);
						// 创建标记点数组
						const markers = this.stationData.map((station, index) => {
							// 确保经纬度有效
							const latitude = station.geographic?.latitude || 0;
							const longitude = station.geographic?.longitude || 0;
							const isValidCoord = latitude !== 0 && longitude !== 0;
							return {
								id: Number(station.code),
								latitude: latitude,
								longitude: longitude,
								iconPath: '/static/marker_active.svg',
								width: 32,
								height: 42,
								// 始终显示标注，不需要点击
								callout: {
									content: station.title || '溜娃车站点',
									color: '#ffffff',
									fontSize: 12,
									borderRadius: 6,
									bgColor: '#4CAF50',
									padding: 5,
									display: 'ALWAYS' // 始终显示标注
								}
							};
						});

						if (markers.length > 0) {
							this.markers = markers;
							uni.showToast({
								title: `已加载${markers.length}个站点`,
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '附近暂无可用车辆',
								icon: 'none'
							});
						}
					} else {
						console.warn('API返回格式不正确:', res.data);
						uni.showToast({
							title: '获取车辆信息失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('网络请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				},
				complete: () => {
					uni.hideLoading();
				}
			});
		},

		chooseLocation() {
			this.blockLocationUpdate = true;
			uni.chooseLocation({
				success: (res) => {
					console.log('选择位置成功:', res);
					this.currentCity = res.address.split("省")[1]
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.mapContext.moveToLocation({
						latitude: res.latitude,
						longitude: res.longitude,
						success: () => {
							console.log('地图已跳转至选择的位置');
						},
						fail: (err) => {
							console.error('地图跳转失败:', err);
						}
					});
					this.updateCurrentCity();
					this.loadNearbyVehicles();
				},
				fail: (err) => {
					console.error('选择位置失败:', err);
					uni.showToast({
						title: '选择位置已取消',
						icon: 'none'
					});
				},
				complete: () => {
					setTimeout(() => {
						this.blockLocationUpdate = false;
					}, 1000);
				}
			});
		},

		onMapRegionChange(e) {
			if (this.blockLocationUpdate || !this.isMapLoaded) return;

			const now = Date.now();

			if (e.type === 'begin') {
				this.isUserAction = true;
				return;
			}

			if (e.type === 'end' && this.isUserAction && (now - this.lastUpdateTime > 1000)) {
				this.lastUpdateTime = now;
				// 更新当前城市信息，但不重新加载车辆以避免频繁请求
				if (!this.apiKeyLimited) {
					this.updateCurrentCity();
				}

				if (this.updateTimer) {
					clearTimeout(this.updateTimer);
				}

				this.isUserAction = false;
			}
		},

		onMapTap(e) {
			// console.log('地图点击:', e);
			// 关闭用户菜单
			if (this.showUserMenu) {
				this.showUserMenu = false;
			}
		},
		bindMobile(e){
			const token = uni.getStorageSync(STORAGE_KEYS.token);
			console.log(e)
			uni.request({
				url: API_CONFIG.baseUrl + '/user.User/bindMobile',
				method: 'POST',
				header: {
					'content-type': 'application/json' // 明确指定内容类型
				},
				data: {
					token:token,
					...e.detail
				},
				timeout: API_CONFIG.timeout,
				success: (res) => {
					if (res.data && res.data.code === 1) {
						this.userInfo.mobile = res.data.data.mobile
						this.onRentTap()
					} else {
						// 登录失败
						uni.showModal({
							title: '提示',
							content: '绑定失败，需要绑定手机后才能使用',
							confirmText: '重新绑定',
							success: (res) => {
								if (res.confirm) {
									// 这里可以直接打开登录弹窗
								}
							}
						});
					}
				},
				fail: (err) => {
					uni.showModal({
						title: '提示',
						content: '需要绑定手机后才能使用',
						confirmText: '去绑定',
						success: (res) => {
							if (res.confirm) {
								// 这里可以直接打开登录弹窗
							}
						}
					});
				}
			});
		},
		// 功能按钮相关方法
		onRentTap() {
			if (!this.isLoggedIn) {
				uni.showModal({
					title: '提示',
					content: '请先登录后再进行操作',
					confirmText: '去登录',
					success: (res) => {
						if (res.confirm) {
							// 这里可以直接打开登录弹窗
						}
					}
				});
				return;
			}
			// 扫描二维码
			uni.scanCode({
				onlyFromCamera: true,
				scanType: ['qrCode'],
				success: (res) => {
					const payload = parseInput(res.result);
					if (!payload) {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
						return;
					}
					const {
						station_id,
						pile_idx
					} = payload;
					if (!station_id || !pile_idx) {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
						return;
					}
					uni.navigateTo({
						url: "/pages/rent/select?station_id=" + station_id + "&pile_idx=" +
							pile_idx
					})
				},
				fail: (err) => {
					console.error('扫码失败:', err);
					uni.showToast({
						title: '扫码已取消',
						icon: 'none'
					});
				}
			});
		},

		onMenuItemTap(item) {
			if (item.name == '我的订单') {
				uni.navigateTo({
					url: "/mine-page/order/order",
					success: () => console.log("跳转成功"),
					fail: (err) => console.error("跳转失败:", err)
				})
			} else if (item.name == '服务中心') {
				uni.navigateTo({
					url: "/problem-page/index/index"
				})
			}
		},


		// 点击站点查看站点详情
		markersClick(event) {
			// 获取当前站点的Id
			const markerId = event.detail.markerId;
			// 从所有站点信息中过滤出当前站点的信息
			this.currentStation = this.stationData.find(
				s => Number(s.code) === markerId
			);
			console.log(this.currentStation);
			// 如果站点信息存在 则展示模态框
			if (this.currentStation) {
				this.showStationPanel = true;
				this.getCartInfoByStationId(Number(this.currentStation.code))
			} else {
				uni.showToast({
					title: '站点信息获取失败',
					icon: 'none'
				});
			}
		},

		// 获取当前站点下的车辆信息
		getCartInfoByStationId(station_id) {
			uni.request({
				url: API_CONFIG.baseUrl + "/babyCar.StationLayout/list?station_id=" + station_id,
				method: "GET",
				success: (res) => {
					// console.log(res.data.data);
					this.currentStationDetail = res.data.data
				},
				fail: (err) => {
					console.error(err);
				}
			})
		}
	}
};
</script>

<style>
/* 全局样式 */
page {
	background-color: #f8f8f8;
	font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC', 'miui', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif;
	color: #333;
}

.app-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	position: relative;
}

/* 头部样式 */
.header {
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	height: 200rpx;
	background-color: #FFD000;
}

.header-content {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 10rpx 0;
	flex: 1;
}

.app-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 10rpx;
	text-align: center;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
}

/* 主体内容样式 */
.main-content {
	flex: 1;
	padding: 20rpx;
}

/* 底部样式 */
.footer {
	background-color: #FFFFFF;
	padding: 20rpx;

}

.location-container {
	display: flex;
	align-items: center;
	background-color: rgba(255, 255, 255, 0.7);
	border-radius: 40rpx;
	padding: 8rpx 20rpx;
	max-width: 40%;
	margin: 10rpx 0;
}

.location-icon {
	font-size: 28rpx;
	margin-right: 8rpx;
	color: #06C167;
}

.location-text {
	font-size: 24rpx;
	font-weight: 500;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.arrow-icon {
	font-size: 18rpx;
	color: #999;
	margin-left: 8rpx;
}

/* 用户菜单 */
.user-menu {
	position: absolute;
	bottom: 280rpx;
	left: 24rpx;
	right: 24rpx;
	background-color: #ffffff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
	z-index: 100;
	overflow: hidden;
}

.menu-item {
	padding: 28rpx 24rpx;
	display: flex;
	align-items: center;
	border-bottom: 1px solid #f0f0f0;
}

.menu-item:last-child {
	border-bottom: none;
}

.menu-item-icon {
	font-size: 36rpx;
	margin-right: 20rpx;
	color: #666;
}

.menu-item-text {
	font-size: 30rpx;
	color: #333;
}

.menu-item.logout .menu-item-text {
	color: #E54340;
}

.menu-item.logout .menu-item-icon {
	color: #E54340;
}

/* 地图样式 */
.map-wrapper {
	flex: 1;
	position: relative;
	overflow: hidden;
}

.map {
	width: 100%;
	height: 100%;
}

.map-controls {
	position: absolute;
	bottom: 180rpx;
	right: 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 20rpx;
}

.control-button {
	width: 80rpx;
	height: 80rpx;
	background-color: #ffffff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.15);
}

.control-icon {
	font-size: 36rpx;
}

.map-legend {
	position: absolute;
	bottom: 180rpx;
	left: 30rpx;
	background-color: rgba(255, 255, 255, 0.9);
	border-radius: 12rpx;
	padding: 16rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.legend-item {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.legend-item:last-child {
	margin-bottom: 0;
}

.legend-marker {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
	margin-right: 10rpx;
}

.legend-marker.active {
	background-color: #06C167;
}

.legend-marker.inactive {
	background-color: #9E9E9E;
}

.legend-marker.current {
	background-color: #00a1f8;
}

.legend-text {
	font-size: 24rpx;
	color: #666;
}

/* 底部面板 */
.bottom-panel {
	background-color: #ffffff;
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.08);
	padding: 30rpx 24rpx;
	z-index: 10;
}

.panel-content {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

/* 用户信息区域 */
.user-profile-container {
	display: flex;
	align-items: center;
	padding: 16rpx;
	background-color: #F4F4F4;
	border-radius: 16rpx;
	margin-bottom: 10rpx;
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
	border: 2rpx solid #FFD000;
}

.user-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.user-name {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 4rpx;
}

.user-status {
	font-size: 24rpx;
	color: yellow;
}

.user-menu-icon {
	font-size: 40rpx;
	color: #999;
	padding: 0 10rpx;
}

.login-button-large {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 90rpx;
	background: #FFD000;
	border-radius: 45rpx;
	border: none;
	font-size: 32rpx;
	font-weight: 500;
	color: #333333;
	box-shadow: 0 4rpx 10rpx rgba(255, 208, 0, 0.3);
	margin-bottom: 10rpx;
}

.primary-button {
	width: 100%;
	height: 88rpx;
	border-radius: 44rpx;
	border: none;
	font-size: 32rpx;
	color: #333;
	background: #FFD700;
	margin: 20rpx 0;
	line-height: 88rpx;
}

.button-icon {
	font-size: 36rpx;
	margin-right: 10rpx;
}

.button-text {
	font-size: 32rpx;
}

/* 底部信息面板 */
.station-panel {
	position: fixed;
	left: 0;
	right: 0;
	bottom: -100%;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
	z-index: 1000;
	max-height: 70vh;
	padding: 32rpx;
}

.panel-visible {
	bottom: 0;
}

/* 关闭按钮 */
.close-btn {
	position: absolute;
	top: 24rpx;
	right: 24rpx;
	padding: 16rpx;
	z-index: 1;
}

/* 遮罩层 */
.panel-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	opacity: 0;
	transition: opacity 0.3s;
	pointer-events: none;
	z-index: 999;
}

.mask-visible {
	opacity: 1;
	pointer-events: auto;
}

/* 内容样式 */
.station-header {
	display: flex;
	align-items: center;
	margin-bottom: 32rpx;
}

.station-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	margin-right: 20rpx;
}


.info-row {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
}

.info-text {
	font-size: 28rpx;
	color: #666;
	margin-left: 12rpx;
}

.divider {
	height: 1px;
	background: #eee;
	margin: 32rpx 0;
}

.section-title {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
	margin-bottom: 24rpx;
}

.price-item {
	display: flex;
	justify-content: space-between;
	padding: 16rpx 0;
}

.price-label {
	color: #666;
}

.price-value {
	color: #ff5722;
	font-weight: 500;
}

.action-buttons {
	margin-top: 40rpx;
	padding: 0 20rpx;
}
</style>